package com.test.webtest.service.impl;

import com.test.webtest.service.FileCleanupService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Objects;

/**
 * @Description FileCleanupServiceImpl
 * @Author jiangzhenghao
 * @Date 2025-05-17  10:53
 */
@Service
public class FileCleanupServiceImpl implements FileCleanupService {

    private static final long DEFAULT_EXPIRATION_DAYS = 7;
    private final String generatedFilePath = "src/main/resources/generated/";

    @Override
    public boolean manualCleanup(long days) {
        return deleteOldFiles(days);
    }

    /**
     * 删除过期文件
     * @param expirationDays 例如：expirationDays = 7 表示删除7天前的文件
     *                       expirationDays = 0 则立即删除所有文件
     * @return
     */
    private boolean deleteOldFiles(long expirationDays) {
        // 如果超过expirationDays，则删除generatedFilePath路径下所有文件
        File directory = new File(generatedFilePath);

        // 检查目录是否存在且是目录
        if (!directory.exists() || !directory.isDirectory()) {
            System.out.println("目录不存在: " + generatedFilePath);
            return false;
        }

        File[] files = directory.listFiles();
        boolean hasDeleted = false;

        if (files == null || files.length == 0) {
            System.out.println("目录为空: " + generatedFilePath);
            return false;
        }

        long currentTime = System.currentTimeMillis();
        long expirationTime = currentTime - expirationDays * 24 * 60 * 60 * 1000; // 转换为毫秒

        for (File file : Objects.requireNonNull(files)) {
            if (file.isFile() && file.lastModified() < expirationTime) {
                if (file.delete()) {
                    System.out.println("已删除文件: " + file.getName());
                    hasDeleted = true;
                } else {
                    System.out.println("无法删除文件: " + file.getName());
                }
            }
        }

        return hasDeleted;
    }

    /**
     * 定时任务，每天凌晨执行一次，删除7天前的文件
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void cleanupOldFiles() {
        deleteOldFiles(DEFAULT_EXPIRATION_DAYS);
    }

}
